<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('模板类型')" prop="templateType">
            <dictSelect
              v-model="form.templateType"
              :clearable="true"
              dictionary="model_data_source_type"
              @change="initDataList"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('业务对象')" prop="busId">
            <el-select v-model="form.busId" filterable :clearable="true" :placeholder="$t('请选择')">
              <el-option
                v-for="item in dataList"
                :key="item.id"
                :label="form.templateType === 'XMGZ' ? item.dealName : item.fundName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('分配模板')" prop="fileId">
            <span slot="label">
              {{ $t('分配模板') }}
              <el-tooltip placement="top">
                <div slot="content">
                  <span v-if="form.fileId">{{ '若需要替换自定义模板，需上传新的模板后保存才可以生效' }}</span>
                  <span v-else>{{ '当前是系统默认模板，若需要替换自定义模板，需上传新的模板后才可以保存才可以生效' }}</span>
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <div v-if="form.fileId">
              <div v-if="form.fileList !== null && form.fileList !== '' && form.fileList !== undefined && form.fileList.length > 0" style="width: 100%;">
                <span :title="form.fileList[0].name" style="cursor: pointer;color: #3da4fc">
                  <i class="el-icon-paperclip" style="margin-right:5px;" />{{ form.fileList[0].name }}
                </span>
                <span style="margin-left:10px">
                  <el-divider direction="vertical" />
                  <el-button type="text" icon="el-icon-download" size="small" @click.native="downLoadFileOpens(form.fileList[0].id)">下载</el-button>
                  <el-upload
                    ref="upload"
                    :limit="1"
                    accept=".xlsx, .xls"
                    :headers="upload.headers"
                    :action="upload.url"
                    :disabled="upload.isUploading"
                    :before-upload="handleBeforeUpload"
                    :on-success="handleFileSuccess"
                    :on-exceed="handleFileExceed"
                    :data="form"
                    class="upload"
                  >
                    <el-button type="text" icon="el-icon-upload" size="small">上传新的模板</el-button>
                  </el-upload>
                </span>
              </div>
            </div>
            <div v-else>
              <span v-if="fileName" :title="fileName" style="cursor: pointer;color: #3da4fc">
                <i class="el-icon-paperclip" style="margin-right:5px;" />{{ fileName }}
              </span>
              <span style="margin-left:10px">
                <el-divider v-if="fileName" direction="vertical" />
                <el-button v-if="fileName" type="text" icon="el-icon-download" size="small" @click.native="downLoadDefaultTemplate(fileName)">下载</el-button>
                <el-upload
                  ref="upload"
                  :limit="1"
                  accept=".xlsx, .xls"
                  :headers="upload.headers"
                  :action="upload.url"
                  :disabled="upload.isUploading"
                  :before-upload="handleBeforeUpload"
                  :on-success="handleFileSuccess"
                  :on-exceed="handleFileExceed"
                  :data="form"
                  class="upload"
                >
                  <el-button type="text" icon="el-icon-upload" size="small">上传新的模板</el-button>
                </el-upload>
              </span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('数据源')" prop="dataSourceId">
            <el-select v-model="form.dataSourceId" filterable :clearable="true" :placeholder="$t('请选择')">
              <el-option
                v-for="item in dataSourceList"
                :key="item.id"
                :label="item.dataSourceName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="24">-->
        <!--          <el-form-item :label="$t('分配规则描述')" prop="ruleDescribe">-->
        <!--            <el-input v-model="form.ruleDescribe" type="textarea" :placeholder="$t('分配规则描述')" show-word-limit maxlength="2000" />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="system:model" />
    </div>
  </div>
</template>

<script>
import { saveModelTemplate, getModelTemplate, checkTemplateBus } from '@/api/system/model/template/modelTemplate'
import { getToken } from '@/utils/auth'
import { findDeal } from '@/api/base/deal/dealBase'
import { findFundFof } from '@/api/fund/fundBase'
import { listModelDataSourceByType } from '@/api/system/model/data/modelDataSource'
import { downLoadFileOpen } from '@/utils/zipdownload'
export default {
  components: {
  },
  data() {
    return {
      // 表单参数
      form: {
        fileList: []
      },
      // 业务对象列表
      dataList: [],
      // 数据源列表
      dataSourceList: [],
      templateTypeOptions: [],
      fileName: undefined,
      // 遮罩层
      loading: false,
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/model/modelTemplate/uploadTemplate',
        // 遮罩层
        loading: false
      },
      // 表单校验
      rules: {
        templateType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        busId: [{ validator: this.checkBusData, trigger: 'change' }],
        dataSourceId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getDicts('model_data_source_type').then(response => {
      this.templateTypeOptions = response.data
    })
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getModelTemplate(data.id).then(response => {
          this.form = response.data
          this.initDataList(this.form.templateType)
          this.form.busId = response.data.busId
          this.form.dataSourceId = response.data.dataSourceId
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 校验业务对象数据
    checkBusData(rule, value, callback) {
      const checkParam = {
        id: this.form.id,
        templateType: this.form.templateType,
        busId: value
      }
      checkTemplateBus(checkParam).then(response => {
        const flag = response.data.flag
        if (flag) {
          callback()
        } else {
          callback(new Error(response.data.msg))
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        templateType: undefined,
        busId: undefined,
        fileId: undefined,
        dataSourceId: undefined,
        ruleDescribe: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        fileList: []
      }
      this.fileName = undefined
      this.dataList = []
      this.dataSourceList = []
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        let flag = true
          if (this.form.fileList.length === 0) {
            this.msgError(this.$t('请上传一份模版'))
            flag = false
        }
        if (valid && flag) {
          this.loading = true
          saveModelTemplate(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    initDataList(data) {
      // this.templateTypeOptions.forEach(item => {
      //   if (item.dictValue === data) {
      //     this.fileName = item.remark
      //   }
      // })
      this.dataList = []
      this.dataSourceList = []
      const fetchDataList = data === 'XMGZ' ? findDeal : findFundFof
      fetchDataList({}).then((response) => {
        this.dataList = response.data
        // 检查 this.form.busId 是否存在于 this.dataList 中
        const busIdExists = this.dataList.some((item) => item.id === this.form.busId)
        if (!busIdExists) {
          this.form.busId = undefined
        }
      })
      listModelDataSourceByType(data).then(res => {
        this.dataSourceList = res.rows
        // 检查 this.form.dataSourceId 是否存在于 this.dataSourceList 中
        const dataSourceIdExists = this.dataSourceList.some((item) => item.id === this.form.dataSourceId)
        if (!dataSourceIdExists) {
          this.form.dataSourceId = undefined
        }
      })
    },
    downLoadFileOpens(id) {
      downLoadFileOpen(id)
    },
    // 下载系统默认计算模板
    downLoadDefaultTemplate(fileName) {
      this.downLoadExcel('/model/modelTemplate/download/' + fileName)
    },
    handleBeforeUpload(file, fileList) {
      console.log(fileList)
      // .xlsx.xls格式文件
      var flag = false
      const availableSuffixes = '.xlsx.xls'
      const suffix = file.name.substr(file.name.lastIndexOf('.') + 1, file.name.length)
      if (!availableSuffixes.includes(suffix)) {
        flag = true
      }
      if (flag) {
        this.msgError(this.$t('仅支持导入 xlsx、xls格式文件！'))
        this.$refs.upload.clearFiles()
        return false
      }
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      if (response.code === 200) {
        console.log(response.data, 'response.data')
        this.form.fileList = [{ id: response.data.id, name: response.data.name }]
        this.form.fileId = response.data.id
        this.msgSuccess(this.$t('上传成功'))
      } else if (response.code === 500) {
        this.msgError(this.$t('数据异常'))
      } else {
        this.$notify({
          title: this.$t(response.msg),
          message: '',
          type: 'success'
        })
      }
    },
    // 文件达到上限处理
    handleFileExceed() {
      this.msgError(this.$t('可上传文件数量已达到上限'))
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/.upload {
  margin-left: 15px;
  display: inline-block !important;
  .el-upload-list {
    display: none;
  }
}
</style>
